<template>
  <div class="mod-user">
    <el-form :form="query" :inline="true" @keyup.enter.native="getAdminList()">
      <el-form-item>
        <el-input v-model="query.name" placeholder="用户名/手机号" clearable></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="success" icon="el-icon-search" v-if="hasPermission(['system:admin:list'])" @click="searchAdmin">查询</el-button>
        <el-button v-if="hasPermission(['system:admin:save'])" type="primary" @click="addAdmin">新增</el-button>
        <!--<el-button v-if="hasPermission(['system:admin:batchDelete'])" @click="getAdminList()" type="danger">批量删除</el-button>-->
      </el-form-item>
    </el-form>
    <el-table
      :data="dataList"
      border
      @selection-change="selectionChangeHandle"
      v-loading="loading"
      style="width: 100%;">

      <el-table-column
        prop="login_name"
        header-align="center"
        align="center"
        width="100"
        label="账号">
      </el-table-column>

      <el-table-column
        prop="name"
        header-align="center"
        align="center"
        width="80"
        label="姓名">
      </el-table-column>

      <el-table-column
        prop="mobile"
        header-align="center"
        align="center"
        width="120"
        label="手机号">
      </el-table-column>

      <el-table-column
        prop="school_name"
        header-align="center"
        align="center"
        :show-overflow-tooltip="true"
        width="120"
        label="所属学校">
      </el-table-column>

      <el-table-column
        prop="login_count"
        header-align="center"
        align="center"
        width="80"
        label="登录次数">
      </el-table-column>

      <el-table-column
        prop="login_ip"
        header-align="center"
        align="center"
        min-width="100"
        label="登录ip">
      </el-table-column>

      <el-table-column
        prop="disabled_flag"
        header-align="center"
        align="center"
        width="80"
        label="状态">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.disabled_flag" size="small" type="danger">禁用</el-tag>
          <el-tag v-else size="small">正常</el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="last_login_date"
        header-align="center"
        align="center"
        min-width="140"
        :formatter="formatterLastLoginDate"
        label="最后登录时间">
      </el-table-column>

      <el-table-column
        prop="create_date"
        header-align="center"
        align="center"
        min-width="140"
        :formatter="formatterCreateDate"
        label="创建时间">
      </el-table-column>

      <el-table-column
        header-align="center"
        align="center"
        width="250"
        label="操作">
        <template slot-scope="scope">
          <el-button
            icon="el-icon-setting"
            size="small"
            v-if="hasPermission(['system:admin:updatePassword'])"
            @click="resettingPassword(scope.row)"
            type="text">重置密码</el-button>
          <el-button
            v-if="hasPermission(['system:admin:update'])"
             @click="updateAdmin(scope.row)"
            size="small"
             icon="el-icon-edit"
             type="text">修改</el-button>
          <el-button
            v-if="hasPermission(['system:admin:deleteById'])"
            @click="deleteAdminById(scope.row)"
            size="small"
            icon="el-icon-delete"
            type="text">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      title="重置密码"
      :close-on-click-modal="false"
      :visible.sync="passwordFlag">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordForm" @keyup.enter.native="updatePassword()" label-width="80px">
        <el-form-item label="密码" prop="password">
          <el-input type="password" v-model="passwordForm.password" placeholder="密码"></el-input>
        </el-form-item>

        <el-form-item label="确认密码" prop="name">
          <el-input type="password" v-model="passwordForm.confirmPassword" placeholder="确认密码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer"  class="dialog-footer">
        <el-button @click="passwordFlag = false">取消</el-button>
        <el-button type="primary" @click="updatePassword()">修改</el-button>
      </span>
    </el-dialog>

    <el-dialog
      :title="!form.id ? '新增管理员' : '修改管理员'"
      :close-on-click-modal="false"
      :visible.sync="showFlag">
      <el-form :model="form" :rules="rules" ref="form" label-width="80px">
        <el-form-item label="账号" prop="login_name">
          <el-input v-model="form.login_name" placeholder="登录帐号"></el-input>
        </el-form-item>

        <el-form-item label="所属学校">
          <el-select
            v-model="form.school_id"
            filterable
            clearable
            placeholder="所属学校">
            <el-option
              v-for="item in schoolList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" auto-complete="off" placeholder="姓名"></el-input>
        </el-form-item>

        <template v-if="!form.id">
          <el-form-item label="密码" prop="password" :class="{ 'is-required': !form.id }">
            <el-input v-model="form.password" @focus="changeInputType" :type="passwordType" placeholder="密码"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="confirmPassword" :class="{ 'is-required': !form.id }">
            <el-input v-model="form.confirmPassword" :type="passwordType" placeholder="确认密码"></el-input>
          </el-form-item>
        </template>

        <el-form-item label="手机号">
          <el-input v-model="form.mobile" placeholder="手机号"></el-input>
        </el-form-item>

        <el-form-item label="角色" size="mini" prop="roleIdList">
          <el-checkbox-group v-model="form.roleIds">
            <el-checkbox
              v-for="role in roleList"
              :key="role.id"
              :label="role.id">{{role.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>

        <el-form-item label="状态" size="mini" prop="status">
          <el-radio-group v-model="form.disabled_flag">
            <el-radio :label="0">正常</el-radio>
            <el-radio :label="1">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <span slot="footer"  class="dialog-footer">
        <el-button @click="showFlag = false">取消</el-button>
        <el-button type="primary" @click="saveOrUpdate()">确定</el-button>
      </span>
    </el-dialog>

    <el-pagination
      background
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      :total="totalCount"
      layout="total, sizes, prev, pager, next, jumper">
    </el-pagination>
  </div>
</template>

<script>
  import { isMobile } from '@/utils/validate'
  import { getSchoolList } from '@/utils/education-api'
  export default {
    name: 'admin',
    data () {
      let validateConfirmPassword = (rule, value, callback) => {
        if (!value) {
          callback(new Error('确认密码不能为空'))
        } else {
          if (this.form.password !== value) {
            callback(new Error('确认密码与密码输入不一致'))
          } else {
            callback()
          }
        }
      }
      return {
        currentPage: 1,
        pageSize: 10,
        totalCount: 0,
        loading: true,
        dataList: [],
        roleList: [],
        showFlag: false,
        passwordType: 'text',
        adminId: '',
       // checkedRoleIds: [],
        form: {
          login_name: '',
          name: '',
          password: '',
          confirmPassword: '',
          mobile: '',
          school_id: '',
          roleIds: [],
          disabled_flag: 0
        },
        query: {
          name: ''
        },
        checkRoleIds: [],
        passwordFlag: false,
        passwordForm: {
          password: '',
          confirmPassword: ''
        },

        schoolList: [],
        passwordRules: {
          password: [
            {required: true, message: '请输入密码', trigger: 'blur'}
          ],
          confirmPassword: [
            {required: true, message: '请输入确认密码', trigger: 'blur'}
          ]
        },
        rules: {
          login_name: [
            {required: true, message: '用户名不能为空', trigger: 'blur'}
          ],
          password: [
            {required: true, message: '请输入登录密码', trigger: 'blur'}
          ],
          confirmPassword: [
            { required: true, validator: validateConfirmPassword, trigger: 'blur' }
          ]
        }
      }
    },

    mounted () {
      let that = this
      that.getAdminList()
      that.getRoleList()
      getSchoolList(function (data) {
        that.schoolList = data
      })
    },

    methods: {
      // 重置密码
      resettingPassword (row) {
        this.adminId = row.id
        this.passwordFlag = true
      },
      searchAdmin () {
        this.currentPage = 1
        this.getAdminList()
      },
      addAdmin () {
        this.showFlag = true
        this.form = {
          login_name: '',
          name: '',
          password: '',
          confirmPassword: '',
          school_id: '',
          mobile: '',
          roleIds: [],
          disabled_flag: 0
        }
      },
      changeInputType () {
        this.passwordType = 'password'
      },
      updatePassword () {
        let that = this
        that.passwordForm.id = that.adminId
        that.$refs['passwordForm'].validate(function (valid, rules) {
          if (valid) {
            that.axios.post(that.$http.httpUrl('/system/admin/updatePassword'), that.passwordForm)
              .then(function (response) {
                that.visible = false
                if (response.data.code === 1) {
                  that.$message({
                    type: 'success',
                    message: response.data.message
                  })
                  that.passwordFlag = false
                  that.passwordForm.password = ''
                  that.passwordForm.confirmPassword = ''
                } else {
                  that.$message({
                    type: 'error',
                    message: response.data.message
                  })
                }
              }).catch(function (error) {
                console.log(error)
              })
          } else {
            let message = ''
            for (let rule in rules) {
              message = rules[rule][0].message
              if (message) {
                break
              }
            }
            that.$message({
              type: 'error',
              message: message
            })
            return false
          }
        })
      },
      // 获取数据列表
      getAdminList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/admin/list'), {
          params: {
            offset: (that.currentPage - 1) * that.pageSize,
            limit: that.pageSize,
            name: that.query.name
          }
        }).then(function (response) {
          that.loading = false
          that.dataList = response.data.data.dataList
          that.totalCount = response.data.data.total
        })
      },

      formatterCreateDate (row, column) {
        if (!row.create_date) {
          return '--'
        }
        return this.moment(row.create_date).format('YYYY-MM-DD HH:mm')
      },

      formatterLastLoginDate (row, column) {
        if (!row.last_login_time) {
          return '--'
        }
        return this.moment(row.last_login_time).format('YYYY-MM-DD HH:mm')
      },
      // 每页数
      sizeChangeHandle (val) {
        this.pageSize = val
        this.getAdminList()
      },
      // 当前页
      currentChangeHandle (val) {
        this.currentPage = val
        this.getAdminList()
      },

      // 多选
      selectionChangeHandle (val) {
        this.checkedIds = val
      },

      getRoleList () {
        let that = this
        that.axios.get(that.$http.httpUrl('/system/role/list'), {
          params: {
            sqlId: 'system.role.list'
          }
        }).then(function (response) {
          that.roleList = response.data.data.dataList
        })
      },

      // 表单提交
      saveOrUpdate () {
        let that = this
        if (that.form.mobile) {
          if (!isMobile(that.form.mobile)) {
            that.$message({
              type: 'error',
              message: '请输入正确手机号'
            })
            return
          }
        }
        that.save()
      },

      save () {
        let that = this
        that.$refs['form'].validate(function (valid, rules) {
          if (valid) {
            that.axios.post(that.$http.httpUrl('/system/admin'), that.form)
              .then(function (response) {
                that.visible = false
                if (response.data.code === 1) {
                  that.$message({
                    type: 'success',
                    message: response.data.message
                  })
                  that.showFlag = false
                  that.getAdminList()
                } else {
                  that.$message({
                    type: 'error',
                    message: response.data.message
                  })
                }
              }).catch(function (error) {
                console.log(error)
              })
          } else {
            let message = ''
            for (let rule in rules) {
              message = rules[rule][0].message
              if (message) {
                break
              }
            }
            that.$message({
              type: 'error',
              message: message
            })
            return false
          }
        })
      },

      // 新增 / 修改
      updateAdmin (item) {
        this.form = {
          id: item.id,
          login_name: item.login_name,
          name: item.name,
          mobile: item.mobile,
          school_id: item.school_id,
          disabled_flag: item.disabled_flag ? 1 : 0,
          roleIds: item.roleIds
        }
        this.showFlag = true
        this.form.disabled_flag = item.disabled_flag ? 1 : 0
      },

      batchDelete () {
        let that = this
        that.$confirm('确定删除选中的管理员?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          that.axios.delete(that.$http.httpUrl('/system/admin/batchDelete'), {
            data: {
              ids: that.checkIds,
              sqlId: 'system.common.batchDeleteByIds',
              table: 'system_admin'
            }
          }).then(function (response) {
            if (response.data.code === 1) {
              that.$message({
                type: 'success',
                message: response.data.message
              })
              that.getAdminList()
            } else {
              that.$message({
                type: 'error',
                message: response.data.message
              })
            }
          })
        })
      },

      // 删除
      deleteAdminById (item) {
        let that = this
        that.$confirm('确定删除管理员' + item.login_name + '?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(function () {
          that.axios.delete(that.$http.httpUrl('/system/admin'), {
            data: item
          }).then(function (response) {
            if (response.data.code === 1) {
              that.$message({
                type: 'success',
                message: response.data.message
              })
              that.getAdminList()
            } else {
              that.$message({
                type: 'error',
                message: response.data.message
              })
            }
          })
        })
      }
    }
  }
</script>
